﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Globalization;
using System.Xml;

namespace Nuane.Posterous
{
	/// <summary>
	/// The content of a newly posted posterous post.
	/// </summary>
	public class PosterousPostInfo
	{
		//<post>
		//  <id>1234567</id>
		//  <url>http://post.ly/abc123</url>
		//  <longurl>http://sachin.posterous.com/sunday-brunch-in-san-francisco</longurl>
		//  <title>Sunday brunch in San Francisco</title>
		//  <commentsenabled>true</commentsenabled>
		//</post>

		private readonly PosterousSession _session;

		/// <summary>
		/// Gets the short Post.ly URI of this post.
		/// </summary>
		/// <value>Short URI.</value>
		public Uri ShortUri { get; private set; }

		/// <summary>
		/// Gets the Post.ly shortcode of this post (the ABCD part in http://post.ly/ABCD). Can be used in <see cref="PosterousSession.GetPost(string)"/>
		/// </summary>
		public string ShortCode
		{
			get { return ShortUri.Segments[1]; }
		}

		/// <summary>
		/// Gets the full URI of this post.
		/// </summary>
		/// <value>Full URI.</value>
		public Uri Uri { get; private set; }

		/// <summary>
		/// Gets the title of this post.
		/// </summary>
		/// <value>Post title.</value>
		public string Title { get; private set; }

		/// <summary>
		/// Gets the ID of this post.
		/// </summary>
		/// <value>Post ID.</value>
		public int Id { get; private set; }

		/// <summary>
		/// Gets a value indicating whether comments are enabled for this post.
		/// </summary>
		/// <value>True if enabled; false if disabled.</value>
		public bool CommentsEnabled { get; private set; }

		internal PosterousPostInfo(PosterousSession session, XmlNode post)
		{
			_session = session;

			if (post.Name != "post")
				throw new PosterousException("Invalid response.", PosterousExceptionStatus.ServerProtocolViolation);

			ShortUri = Helper.ToUri(Helper.GetChildElementValue(post, "url"));
			Uri = Helper.ToUri(Helper.GetChildElementValue(post, "longurl"));
			Title = Helper.GetChildElementValue(post, "title");
			Id = Helper.ToInt32(Helper.GetChildElementValue(post, "id"));
			CommentsEnabled = Helper.ToBoolean(Helper.GetChildElementValue(post, "commentsenabled"));
		}

		internal PosterousPostInfo(PosterousSession session, PosterousPost post)
		{
			ShortUri = post.ShortUri;
			Uri = post.Uri;
			Title = post.Title;
			Id = post.Id;
			CommentsEnabled = post.CommentsEnabled;
		}

		/// <summary>
		/// Retrieves a full post for this post info. Only work for non-private posts.
		/// </summary>
		/// <returns>Full posterous post.</returns>
		public PosterousPost ToFullPost()
		{
			return _session.GetPost(ShortCode);
		}

	}
}
